package com.liu.stockmarket.ui.search

import android.content.Context
import android.os.Bundle
import androidx.appcompat.widget.SearchView
import androidx.core.os.bundleOf
import androidx.lifecycle.ViewModelProvider
import com.liu.stockmarket.BaseActivity
import com.liu.stockmarket.R
import com.liu.stockmarket.StockMarketApplication
import com.liu.stockmarket.databinding.ActivitySearchBinding
import com.liu.stockmarket.model.Stock
import com.liu.stockmarket.repository.database.entity.StockEntity
import com.liu.stockmarket.ui.stock.add.StockAddActivity
import com.liu.stockmarket.utils.start
import com.liu.stockmarket.utils.toast
import java.math.BigDecimal
import java.time.LocalDate

class SearchActivity : BaseActivity() {
    private lateinit var binding: ActivitySearchBinding
    private lateinit var mAdapter: SearchResultAdapter
    private lateinit var viewModel: SearchViewModel

    private lateinit var stockListFormDB: List<StockEntity>

    override fun initView(savedInstanceState: Bundle?) {

        binding = ActivitySearchBinding.inflate(layoutInflater)
        setContentView(binding.root)
        setToolbar(binding.toolbar.toolbar, true)

        val stockMarketApplication = this.application as StockMarketApplication

        viewModel = ViewModelProvider(
            this,
            SearchViewModel.SearchViewModelFactory(
                stockMarketApplication.easyMoneyRepository,
                stockMarketApplication.stockRepository
            )
        ).get(SearchViewModel::class.java)


        title = "搜索"
        mAdapter = SearchResultAdapter()

        with(binding.searchResult) {
            adapter = mAdapter
        }


    }

    override fun listener() {
        search("代码/名称/首字母", object : SearchView.OnQueryTextListener {
            override fun onQueryTextSubmit(query: String): Boolean {
                doSearch(query)

                return false
            }

            override fun onQueryTextChange(newText: String?): Boolean {
                if (!newText.isNullOrEmpty()) {
                    doSearch(newText)
                } else {
                    mAdapter.setList(mutableListOf())
                    mAdapter.setEmptyView(R.layout.rv_empty_view)
                }
                return true
            }
        })
        mAdapter.setOnItemClickListener { adapter, view, position ->
            val item = adapter.getItem(position) as SearchResultAdapter.Item
            view.requestFocusFromTouch()
            when (item.stockType) {
                Stock.StockType.STOCK, Stock.StockType.BOND, Stock.StockType.FUND -> {
                    StockAddActivity.start(this, item)
                }
                else -> {
                    this.toast("尚不支持该类型的股票")
                }
            }
        }
        mAdapter.setOnItemChildClickListener { adapter, view, position ->
            val item = adapter.getItem(position) as SearchResultAdapter.Item
            view.requestFocusFromTouch()
            when (view.id) {
                R.id.iv_img ->
                    if (item.selfId != null) {
                        deleteSelf(item.selfId)
                    } else {
                        addSelf(item)
                    }

                else -> {
                    println("hhhhh")
                }
            }
        }

    }

    private fun deleteSelf(selfId: Long) {
        viewModel.doDelete(selfId)
        this.toast("删除自选成功")
        finish()
    }

    private fun addSelf(stock: SearchResultAdapter.Item) {
        val stockEntity = StockEntity(
            id = null,
            code = stock.code,
            name = stock.name,
            stockType = stock.stockType,
            transactionExchange = stock.transactionExchange,
            holdingPrice = BigDecimal.ZERO,
            holdingNumber = BigDecimal.ZERO,
            firstTransactionDate = LocalDate.now(),
            self = true
        )
        viewModel.doSave(stockEntity)
        this.toast("添加自选成功")
        finish()
    }


    override fun observer() {

        viewModel.stockList.observe(this) {

            if (it.isNullOrEmpty()) {
                mAdapter.setList(mutableListOf())
                mAdapter.setEmptyView(R.layout.rv_empty_view)

            } else {
                mAdapter.setList(stockToAdapterItem(it))
            }
        }

        viewModel.stockListFromDB.observe(this) {
            stockListFormDB = it
        }
    }

    private fun stockToAdapterItem(stocks: List<Stock>): List<SearchResultAdapter.Item> {

        return stocks.map {
            val self = stockListFormDB.find { stockEntity ->
                stockEntity.code == it.Code && stockEntity.name == it.Name
                        && stockEntity.self
            }
            val transaction = stockListFormDB.find { stockEntity ->
                stockEntity.code == it.Code && stockEntity.name == it.Name
                        && !stockEntity.self
            }

            SearchResultAdapter.Item(
                transaction?.id,
                it.Code, it.Name, it.SecurityTypeName,
                Stock.StockType.securityTypeToStockType(it.SecurityType),
                Stock.TransactionExchange.marketTypeToTransactionExchange(it.MarketType),
                self?.id, transaction?.id
            )
        }.toList()
    }

    private fun doSearch(query: String) {
        viewModel.doSearch(query)

    }

    companion object {
        fun start(context: Context) {
            context.start(bundleOf(), SearchActivity::class.java)
        }
    }
}